package club.gskj.gulimall.ware.listener;

import club.gskj.common.to.mq.OrderTo;
import club.gskj.common.to.mq.StockLockedTo;
import club.gskj.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RabbitListener(queues = {"stock.release.stock.queue"})
public class StockReleaseListener {

    @Autowired
    private WareSkuService wareSkuService;

    /***
     * 1. 库存自动解锁。
     *  下订单成功，库存锁定成功，接下来的业务抛异常，导致订单回滚，之前锁定的库存就要自动解锁
     * 2. 订单失败
     *  锁库存失败
     *
     *  只要解锁库存消息失败，一定要告诉mq此次解锁是失败的，不能删除此消息。
     */
    @RabbitHandler
    public void handle(StockLockedTo to, Message message, Channel channel) throws IOException {
        System.out.println("收到库存解锁消息");
        try {
            // 消息是第二次即二次以后重新派发过来的
            Boolean redelivered = message.getMessageProperties().getRedelivered();
            wareSkuService.unLock(to);
            // 回复mq消息已收到。服务端删除此消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // 发生异常，拒绝回复MQ消息、重新回队等待其他方法继续监听调用
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            e.printStackTrace();
        }
    }

    @RabbitHandler
    public void handle(OrderTo orderTo, Message message, Channel channel) throws IOException {
        System.out.println("收到订单释放消息，检查库存是否已解锁");
        try {
            wareSkuService.unLock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // 发生异常，拒绝回复MQ消息、重新回队等待其他方法继续监听调用
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            e.printStackTrace();
        }
    }
}
